﻿using ELab.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ELab.Connector
{
    public class UDPReceive
    {
        public event EventHandler<ELabEventArgs> BeginReceiveData;
        Thread receiveThread;
        UdpClient udpServer = null;
        public UdpClient UDP
        {
            get
            {
                if (udpServer == null) udpServer = new UdpClient(11000);
                return udpServer;
            }
        }

        private static UDPReceive _current = null;
        public static UDPReceive Current
        {
            get
            {
                if (_current != null) return _current;
                _current = new UDPReceive();
                return _current;
            }
        }

        private bool isStart = false;
        public void Start()
        {
            receiveThread = new Thread(
                new ThreadStart(ReceiveData));
            receiveThread.IsBackground = true;
            receiveThread.Start();
        }

        public void Stop()
        {
            //cancel thread
            if (receiveThread != null && (receiveThread.ThreadState == ThreadState.Running || receiveThread.ThreadState == ThreadState.Background))
            {
                receiveThread.Abort();
                receiveThread = null;
            }
        }


        private void ReceiveData()
        {
            isStart = true;
            while (isStart)
            {
                var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
                var data = this.UDP.Receive(ref remoteEP);
                if (data != null && BeginReceiveData != null) BeginReceiveData(data, new ELabEventArgs(remoteEP));
            }
        }
    }
}
